package com.example.module.ai.spark.util;

import com.example.framework.common.exception.ServiceException;
import com.example.module.ai.config.SparkAiProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@RequiredArgsConstructor
@Slf4j
public class SparkAiUtils {

    private final SparkAiProperties sparkAiProperties;

    public WebSocket createWebSocket(WebSocketListener webSocketListener) {
        String authUrl;
        try {
            authUrl = getAuthUrl(sparkAiProperties.getHostUrl(), sparkAiProperties.getApiKey(), sparkAiProperties.getApiSecret());
        } catch (Exception e) {
            log.error("获取星火大模型url失败，e: {}", e.getMessage());
            throw ServiceException.of("获取星火大模型url失败");
        }
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
        WebSocket webSocket = client.newWebSocket(request, webSocketListener);
        log.debug("websocket创建完成，request: {}", request);
        return webSocket;
    }

    /**
     * 获取星火大模型url
     *
     * @param hostUrl   星火请求地址
     * @param apiKey    控制台获取 apiKey
     * @param apiSecret 控制台获取 apiSecret
     * @return 星火大模型url
     * @throws Exception 参数加密失败
     */
    private static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URI(hostUrl).toURL();
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        return httpUrl.toString();
    }

}